package com.xxhui.scrolldemo.View;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by hui on 2016/7/24.
 */
public class DrawViewByScrollTo extends View {

    private static final String TAG = "DrawViewScrollTo" ;
    private int lastX;
    private int lastY;
    private int viewWidth;
    private int viewHeight;
    private Paint paint;

    public DrawViewByScrollTo(Context context) {
        super(context);
        initRes();
    }

    public DrawViewByScrollTo(Context context, AttributeSet attrs) {
        super(context, attrs);
        initRes();
    }

    public void initRes(){
        // 给View设置背景颜色，便于观察
        setBackgroundColor(Color.DKGRAY);
        paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.BLACK);
        paint.setTextSize(20);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getRawX();//获取以屏幕左上角为参考系的x坐标
        int y = (int) event.getRawY();//获取以屏幕左上角为参考系的y坐标
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                // 记录触摸点坐标
                lastX = x;
                lastY = y;

                break;
            case MotionEvent.ACTION_MOVE:
                int offsetX = x - lastX;
                int offsetY = y - lastY;
                //scrollBy方法让View里面的内容移动，想要移动view，这个得看看看看view是哪个view的内容，显然当前View是viewGroup的内容，所以getparent再调用方法
                ((View)getParent()).scrollTo(-offsetX,-offsetY);
                break;
            case MotionEvent.ACTION_UP:
                ((View)getParent()).scrollTo(0,0);
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        viewWidth = w;
        viewHeight = h;
    }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            //canvas.translate(viewWidth,viewHeight);
            canvas.drawText("scrollTo()",0,viewHeight/2,paint);
        }
}


